<template>
  <div class="container">
    <el-card>
      <el-form
        ref="topForm"
        :model="form"
        @submit.native.prevent
      >
        <div style="display: flex; justify-content: space-between;">
          <span>
            <el-form-item prop="idNum" style="display: inline-block; width: 300px; margin-right: 12px; margin-bottom: 0;">
              <el-input v-model.trim="form.payeeName" clearable placeholder="搜索主体名称" />
            </el-form-item>
            <el-button type="primary" icon="el-icon-search" @click="searchTableData">搜索</el-button>
          </span>
          <span>
            <el-button v-permission="['f07_01']" type="primary" @click="add">新增主体</el-button>
          </span>
        </div>
      </el-form>
    </el-card>
    <el-card style="margin-top: 12px;">
      <BaseTable
        ref="topicManagementTable"
        :table-data="tableData"
        :table-list="tableList"
        :loading="topicManagementLoading"
        :total="total"
        show-index
        show-pagination
        @pagination="handlePagination"
      >
        <el-table-column
          fixed="right"
          label="操作"
          width="200px"
        >
          <template v-slot="scope">
            <el-button v-permission="['f07_02']" type="text" @click="viewPayeeAccount(scope.row)">查看</el-button>
            <el-button v-permission="['f07_05']" type="text" @click="editPayeeAccountHandle(scope.row)">编辑</el-button>
            <el-button
              v-permission="['f07_03']"
              type="text"
              :disabled="addBankDisabled(scope.row.receivingBankAccountListStr)"
              @click="addBank(scope.row.id, false)"
            >新增银行卡</el-button>
          </template>
        </el-table-column>
      </BaseTable>
    </el-card>
    <el-dialog
      v-if="visible"
      :visible.sync="visible"
      width="80%"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      :show-close="false"
    >
      <template slot="title">
        <div style="text-align:center">{{ title }}</div>
      </template>
      <el-form
        ref="addForm"
        v-loading="loading"
        :model="addForm"
        :rules="rules"
      >
        <el-row>
          <el-col :span="12">
            <el-form-item label="主体名称：" prop="payeeName" label-width="150px">
              <el-input
                v-model.trim="addForm.payeeName"
                clearable
                maxlength="100"
                placeholder="请输入主体名称"
                style="width: 100%;"
                :disabled="isView"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="公司名称：" prop="companyName" label-width="150px">
              <el-input
                v-model="addForm.companyName"
                clearable
                maxlength="100"
                placeholder="请输入公司名称"
                style="width: 100%;"
                :disabled="isView"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="公司地址：" prop="companyAddress" label-width="150px">
              <el-input
                v-model="addForm.companyAddress"
                clearable
                maxlength="200"
                placeholder="请输入公司地址"
                style="width: 100%;"
                :disabled="isView"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="电话：" prop="companyPhone" label-width="150px">
              <el-input
                v-model.trim="addForm.companyPhone"
                clearable
                maxlength="50"
                placeholder="请输入电话"
                style="width: 100%;"
                :disabled="isView"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="邮编：" prop="companyPostcode" label-width="150px">
              <el-input
                v-model.trim="addForm.companyPostcode"
                clearable
                maxlength="50"
                placeholder="请输入邮编"
                :disabled="isView"
                style="width: 100%;"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="ERP code：" label-width="150px" prop="erpCode">
              <el-input
                v-model.trim="addForm.erpCode"
                clearable
                maxlength="50"
                placeholder="请输入ERP系统里该主体的code"
                :disabled="isView"
                style="width: 100%;"
              />
            </el-form-item>
          </el-col>
          <el-col v-if="isView" :span="24">
            <el-form-item label="状态：" prop="payeeStatus" label-width="150px">
              <el-radio v-model="addForm.payeeStatus" :disabled="isView" :label="1">启用</el-radio>
              <el-radio v-model="addForm.payeeStatus" :disabled="isView" :label="0">禁用</el-radio>
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item
          v-if="!isView"
          label="状态："
          prop="payeeStatus"
          style="display: flex; justify-content: center; margin-top: 20px"
        >
          <el-radio v-model="addForm.payeeStatus" :disabled="isView" :label="1">启用</el-radio>
          <el-radio v-model="addForm.payeeStatus" :disabled="isView" :label="0">禁用</el-radio>
        </el-form-item>
        <BaseTable
          v-if="isView"
          :table-data="bankTableData"
          :table-list="banktTableList"
        >
          <el-table-column fixed="right" label="操作" width="100px">
            <template v-slot="scope">
              <el-button type="text" style="margin-right: 10px" @click="editBank(scope.row)">编辑</el-button>
              <el-popconfirm
                title="确定要删除此银行信息？"
                @confirm="deleteBank(scope.row)"
              >
                <el-button slot="reference" type="text">删除</el-button>
              </el-popconfirm>
            </template>
          </el-table-column>
        </BaseTable>
        <el-button
          v-if="isView && hasPermission(roles, 'f07_03')"
          :disabled="bankTableData && bankTableData.length>=10"
          type="primary"
          style="margin-bottom: 20px"
          @click="addBank(payeeAccountId, true)"
        >新增银行卡</el-button>
      </el-form>

      <div v-if="!isView" style="display: flex; justify-content: center;">
        <el-button
          size="medium"
          type="primary"
          :loading="sumbitLoading"
          @click="submitForm('addForm')"
        >确定</el-button>
        <el-button size="medium" @click="visible = false">取消</el-button>
      </div>
      <div v-if="isView" style="display: flex; justify-content: center;">
        <el-button size="medium" @click="closePayeeDialog">关闭</el-button>
      </div>
    </el-dialog>

    <!-- 添加银行或编辑银行 -->
    <BankDialog
      :visible="bankDialogVisible"
      :value="bankData"
      :title="bankDialogTitle"
      width="80%"
      :confirm-loading="confirmBankLoading"
      :loading="bankInfoLoading"
      @closeBankDialog="closeBankDialog"
      @saveData="saveBankDialog"
    />
    <!-- 添加银行或编辑银行 -->
  </div>
</template>

<script>
import BaseTable from '@/components/BaseTable'
import { formatTime, getDictionaryLabel, hasPermission } from '@/utils/tools'
import {
  payeeAccountList,
  createPayeeAccount,
  editPayeeAccount,
  viewPayeeAccount,
  queryAccountList,
  viewAccount,
  deleteAccount,
  updateAccount,
  createBankAccount
} from '@/service/topicManagement'
import { cloneDeep } from 'lodash'
import BankDialog from './components/addBankDialog.vue'
import { mapState, mapActions, mapGetters } from 'vuex'

const companyAddressValidator = (rule, value, callback) => {
  if (!value || (value && value.trim() === '')) {
    return callback(new Error('请输入公司地址'))
  }
  if (value && value.length > 200) {
    return callback(new Error('长度大于200'))
  }
  return callback()
}

const companyNameValidator = (rule, value, callback) => {
  if (!value || (value && value.trim() === '')) {
    return callback(new Error('请输入公司名称'))
  }
  if (value && value.length > 100) {
    return callback(new Error('长度大于100'))
  }
  return callback()
}

const addForm = {
  payeeName: '',
  companyName: '',
  companyAddress: '',
  companyPhone: '',
  companyPostcode: '',
  payeeStatus: 1,
  erpCode: ''
}
const Type = {
  add: 'add',
  edit: 'edit',
  view: 'view'
}
const Title = {
  view: '查看主体',
  edit: '编辑主体',
  add: '新增主体'
}

export default {
  name: 'TopicManagement',
  components: {
    BaseTable,
    BankDialog
  },
  data() {
    const bankAccountValidator = (rule, value, callback) => {
      const reg = /^[0-9]+$/
      if (value === '') {
        callback(new Error('请输入收款账号'))
      } else if (!reg.test(value)) {
        callback(new Error('收款账号必须为数字'))
      } else {
        callback()
      }
    }

    const phoneValidator = (rule, value, callback) => {
      const reg = /^[0-9]+$/
      if (value === '') {
        callback(new Error('请输入电话'))
      } else if (!reg.test(value)) {
        callback(new Error('电话必须为数字'))
      } else {
        callback()
      }
    }
    return {
      form: {
        payeeName: ''
      },
      bankData: {},
      bankTableData: [],
      bankDialogVisible: false,
      confirmBankLoading: false,
      bankInfoLoading: false,
      payeeAccountId: '',
      isNeedQueryBankList: false,
      bankDialogTitle: '新增银行卡',
      banktTableList: [
        {
          prop: 'receivingBankAccount',
          label: '收款账号'
        },
        {
          prop: 'currencyCode',
          label: '币种',
          render: (h, data) => {
            const { row, column: { prop }} = data
            const text = getDictionaryLabel(row[prop], this.currency)
            return <span>{ text }</span>
          }
        },
        {
          prop: 'bankName',
          label: '开户行'
        },
        {
          prop: 'bankAddress',
          label: '银行地址',
          width: '250px'
        },
        {
          prop: 'bankSwift',
          label: 'SWIFT'
        },
        {
          prop: 'updateTime',
          label: '最新更新时间',
          render: (h, data) => {
            const { row, column: { prop }} = data
            const text = row[prop] ? formatTime(row[prop]) : '-'
            return <span>{text}</span>
          }
        }
      ],
      visible: false,
      sumbitLoading: false,
      bankAccountValidator,
      tableData: [],
      tableList: [
        {
          label: '主体名称',
          prop: 'payeeName',
          width: '135px'
        },
        {
          label: '收款账号',
          prop: 'receivingBankAccountListStr',
          width: '300px'
        },
        {
          label: '最新操作时间',
          prop: 'updateTime',
          width: '200px',
          render: function(node, data) {
            const { row, column: { prop }} = data
            const text = formatTime(row[prop])
            return <span>{{ text }}</span>
          }
        },
        {
          label: '状态',
          prop: 'payeeStatus',
          render: function(node, data) {
            const { row, column: { prop }} = data
            const text = row[prop] === 1 ? '启用' : '禁用'
            return <span>{{ text }}</span>
          }
        }
      ],
      pageIndex: 1,
      pageSize: 10,
      total: 0,
      addForm: {},
      currencyOptions: [],
      style: {
        width: '100%'
      },
      inputStyle: {
        width: '154px'
      },
      rules: {
        payeeName: [
          { required: true, message: '请输入主体名称', trigger: 'blur' },
          { min: 1, max: 100, message: '长度在 1 到 100 个字符', trigger: 'blur' }
        ],
        companyName: [
          { required: true, validator: companyNameValidator, trigger: 'blur' }
        ],
        companyAddress: [
          { required: true, validator: companyAddressValidator, trigger: 'blur' }
        ],
        companyPhone: [
          { required: true, validator: phoneValidator, trigger: 'blur' },
          { min: 1, max: 50, message: '长度在 1 到 50 个字符', trigger: 'blur' }
        ],
        companyPostcode: [
          { required: true, message: '请输入邮编', trigger: 'blur' },
          { min: 1, max: 50, message: '长度在 1 到 50 个字符', trigger: 'blur' }
        ],
        currencyCode: [
          { required: true, message: '请选择币种', trigger: 'blur' }
        ],
        erpCode: [
          { required: true, message: '请输入ERP code', trigger: 'blur' }
        ]
      },
      type: Type.add,
      loading: false,
      topicManagementLoading: false
    }
  },
  computed: {
    ...mapGetters(['roles']),
    ...mapState({
      currency: state => state.base.currency
    }),
    title() {
      return Title[this.type]
    },
    isView() {
      return this.type === Type.view
    }
  },
  mounted() {
    this.searchTableData()
    this.initBaseData('currency', 'currencyOptions')
  },
  methods: {
    hasPermission,
    ...mapActions({
      getBaseDataList: 'base/getBaseDataList'
    }),
    initAddForm() {
      this.addForm = cloneDeep(addForm)
    },
    searchTableData() {
      this.pageIndex = 1
      this.pageSize = 10
      this.$refs.topicManagementTable.pageIndex = 1
      this.$refs.topicManagementTable.pageSize = 10
      this.getTableData()
    },
    getTableData() {
      this.topicManagementLoading = true
      const params = {
        pageNum: this.pageIndex,
        pageSize: this.pageSize,
        ...this.form
      }
      payeeAccountList({ ...params }).then(res => {
        const { records, total } = res
        this.tableData = records
        this.total = total
      }).finally(() => {
        this.topicManagementLoading = false
      })
    },
    initBaseData(type, optionName) {
      this.$store.dispatch('base/getBaseDataList', { type }).then(res => {
        this[optionName] = res
      })
    },
    add() {
      Object.keys(this.rules).forEach(rule => {
        this.rules[rule][0].required = true
      })
      this.type = Type.add
      this.initAddForm()
      this.visible = true
    },
    viewPayeeAccount(data) {
      Object.keys(this.rules).forEach(rule => {
        this.rules[rule][0].required = false
      })
      this.type = Type.view
      this.getItemData(data)
      const { id } = data
      this.payeeAccountId = id
      this.getAccountBankList(id)
    },
    editPayeeAccountHandle(data) {
      Object.keys(this.rules).forEach(rule => {
        this.rules[rule][0].required = true
      })
      this.type = Type.edit
      this.getItemData(data)
    },
    async getItemData(data) {
      const { id } = data
      this.loading = true
      this.visible = true
      this.addForm = await viewPayeeAccount({ id }).finally(() => {
        this.loading = false
      })
    },
    submitForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          this.sumbitLoading = true
          const isAdd = this.type === Type.add
          const message = isAdd ? '新增成功！' : '编辑成功'
          const fn = isAdd ? createPayeeAccount : editPayeeAccount
          fn({ ...this.addForm }).then(() => {
            this.$message({
              type: 'success',
              message
            })
            this.visible = false
            this.searchTableData()
          })
            .finally(() => {
              this.sumbitLoading = false
            })
        } else {
          return false
        }
      })
    },
    handlePagination(data) {
      const { pageIndex, pageSize } = data
      this.pageIndex = pageIndex
      this.pageSize = pageSize
      this.getTableData()
    },
    addBank(payeeAccountId, bool) {
      this.isNeedQueryBankList = bool
      this.payeeAccountId = payeeAccountId
      this.bankData = {}
      this.bankDialogTitle = '新增银行卡'
      this.bankDialogVisible = true
    },
    async editBank(data) {
      this.bankDialogTitle = '编辑银行卡'
      this.bankDialogVisible = true
      this.getBankInfo(data)
    },
    async deleteBank(data) {
      this.loading = true
      const { id, payeeAccountId } = data
      await deleteAccount({ id }).finally(() => {
        this.loading = false
      })
      this.$message({
        type: 'success',
        message: '删除成功'
      })
      this.getAccountBankList(payeeAccountId)
      this.getTableData()
    },
    closeBankDialog() {
      this.bankDialogVisible = false
    },
    saveBankDialog(data) {
      this.confirmBankLoading = true
      this.bankInfoLoading = true
      if (!data.id) {
        this.addBankHandle(data)
      } else {
        this.updateBankHandle(data)
      }
    },
    async getAccountBankList(id) {
      this.loading = true
      this.bankTableData = await queryAccountList({ payeeAccountId: id }).finally(() => {
        this.loading = false
      })
    },
    async getBankInfo(data) {
      const { id } = data
      this.bankInfoLoading = true
      this.bankData = await viewAccount({ id }).finally(() => {
        this.bankInfoLoading = false
      })
    },
    async addBankHandle(data) {
      await createBankAccount({
        ...data,
        payeeAccountId: this.payeeAccountId
      }).finally(() => {
        this.confirmBankLoading = false
        this.bankInfoLoading = false
      })
      this.bankDialogVisible = false
      this.$message({
        type: 'success',
        message: '添加银行成功'
      })
      if (this.isNeedQueryBankList) {
        this.getAccountBankList(this.payeeAccountId)
      }
      this.searchTableData()
    },
    async updateBankHandle(data) {
      await updateAccount(
        {
          ...data,
          payeeAccountId: this.payeeAccountId
        }
      ).finally(() => {
        this.confirmBankLoading = false
        this.bankInfoLoading = false
      })
      this.$message({
        type: 'success',
        message: '编辑银行成功'
      })
      this.bankDialogVisible = false
      this.getAccountBankList(this.payeeAccountId)
      this.searchTableData()
    },
    closePayeeDialog() {
      this.visible = false
    },
    addBankDisabled(bankAccountStr) {
      let bool
      if (bankAccountStr) {
        const bankAccountList = bankAccountStr.split(',')
        if (bankAccountList && bankAccountList.length >= 10) {
          bool = true
        } else {
          bool = false
        }
      } else {
        bool = false
      }
      return bool
    }
  }
}
</script>

<style scoped lang="scss">
.container {
  margin: 12px;
  width: calc(100% - 24px);
}
</style>
